package com.travelsky.login.resource;

import com.travelsky.login.api.DepartmentProjectionDto;
import com.travelsky.login.api.LoginRequest;
import com.travelsky.login.api.LoginResponse;
import com.travelsky.login.api.UserProjectionDto;
import com.travelsky.login.domain.Account;
import com.travelsky.login.domain.Department;
import com.travelsky.login.domain.User;
import com.travelsky.login.service.LoginService;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class LoginResource {

  private final LoginService loginService;

  @Autowired
  public LoginResource(LoginService loginService) {
    this.loginService = loginService;
  }

  @PostMapping("/login")
  public LoginResponse login(@Valid @RequestBody LoginRequest loginRequest) {
    // 使用用户名和密码进行登录
    User user = doLogin(loginRequest.getUserId(), loginRequest.getPassword());
    // 组装登录响应对象
    return buildLoginResponse(user);
  }

  private User doLogin(String userId, String password) {
    return loginService.login(userId, password);
  }

  private LoginResponse buildLoginResponse(User user) {
    Account account = user.getAccount();
    return new LoginResponse()
        .setLastLoginTime(account.getLastLoginTime())
        .setUserId(account.getUserId())
        .setUserProjectionDto(buildUserProjectionDto(user));
  }

  private UserProjectionDto buildUserProjectionDto(User user) {
    return new UserProjectionDto()
        .setUserName(user.getUserName())
        .setMobile(user.getMobile())
        .setDepartmentProjectionDto(
            buildDepartmentProjectionDto(user.getDepartment()));
  }

  private DepartmentProjectionDto buildDepartmentProjectionDto(Department department) {
    return new DepartmentProjectionDto()
        .setDepartmentName(department.getDepartmentName());
  }

}
